import { ref,inject } from 'vue'
import { user_Store } from './user'
import { communityStore } from './community'
import { musicStore } from './music'
import { ChatStore } from './chat'
import { get_room_info_by_room_id_type} from"../api/chat/room.js"

const provideALL = (app, key, factory,callback=()=>{}) => {
 
  let store = ref(null); // 使用 ref 包裹以支持响应式
    app.provide(key, () => {
    if (!store.value) {
      // 首次注入时初始化 Store
      store.value = factory();
      // 若有初始化项目就执行回调,此处采用在provide里处理
      callback()
      }
    return store;
  });
};

const deal_room_history_byId = async () => {
  // 这里能用inject是因为这些是仓库初始化,是被注入到vue的上下文里的。
  // 当然你可以直接获取一个上下文进行随意的执行
  //在这里更新历史信息
  const roomdb = inject('cacahe_room_info')
  const user = inject('user')()
  const chat= inject('chat')()
  // console.log(user.value.get_user()?.id)
  let groups = []
  let doubles = []
  const user_id=user.value?.get_user()?.id
  roomdb.getAllData().then(async(res) => {
    if (res.length > 0) {
      res.forEach((item) => {
        if (item?.type === 'group') {
          groups.push(item?.room_id)
        } else {
          doubles.push(item?.room_id)
        }
      })
      let data1 = {}, data2 = {};
      if (groups.length > 0) {
        data1 = await get_room_info_by_room_id_type(groups, 'group', user_id) || {}
      }
      
      if (doubles.length > 0) {
        data2 = await get_room_info_by_room_id_type(doubles, 'double', user_id) || {}
      }
      
      const data = Object.assign(data1, data2)
      // 注意Object.assign会影响data1的原数据,他是将data2的值赋给data1,而不是合并
      chat.value.set_current_chat_list(data)
      //执行更新操作
    }
  })
}

export const provide_user = (app) => provideALL(app,'user', user_Store)
export const provide_music = (app) => provideALL(app,'music', musicStore)
export const provide_community = (app) => provideALL(app, 'community', communityStore)
export const provide_chat=(app)=> provideALL(app,'chat', ChatStore,deal_room_history_byId)